package com.linghu.linghu_chatgpt;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {
    private EditText quessEditText;
    private TextView ansTextView;
    private Button submitButton;
    private String responseData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        quessEditText = findViewById(R.id.input_text);
        ansTextView = findViewById(R.id.answer_text);
        submitButton = findViewById(R.id.submit_button);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequest();
            }
        });
    }

    @SuppressLint("StaticFieldLeak")
    private void sendRequest() {
        String ques = quessEditText.getText().toString();
        if (ques != null && !ques.isEmpty()) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), ques);
                    Request request = new Request.Builder()
//                            .url("http://10.0.2.2:9999/lingHuApi/mode?ques="+ques)//本地
                            .url("http://103.117.121.52:8080/lingHuApi/mode?ques="+ques)//个人服务器
//                            .url("http://192.168.10.132:9999/lingHuApi/mode")//公司服务器
                            .post(body)
                            .build();
                    try {
                        Response response = client.newCall(request).execute();
                        if (!response.isSuccessful())
                            throw new IOException("Unexpected code " + response);
                        responseData = response.body().string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                    Log.d("resp=", "responseData");
                    ansTextView.setText(responseData); // 将返回的内容展示到文本框中
                }
            }.execute(); // 执行异步任务，将ques作为参数传递给AsyncTask的execute方法。
        }
    }
}
